package com.ufox.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.UUID;

public class PicUtil {

    public static String getPicUrl(MultipartFile touxiang,String bookImage,String picUrl) throws IOException {
        //0 判断是否上传
        String fileName = touxiang.getOriginalFilename();
        if (org.springframework.util.StringUtils.isEmpty(fileName)) {
            return "upload error!!";
        }

        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);

        String uuid = UUID.randomUUID().toString().replace("-", "");


        Calendar calendar = Calendar.getInstance();
        DecimalFormat df = new DecimalFormat("00");

        String day = df.format(calendar.get(Calendar.DAY_OF_MONTH));
        int year = calendar.get(Calendar.YEAR);
        String month = df.format(calendar.get(Calendar.MONTH) + 1);

        File file = new File(picUrl + year + "/" + month + "/" + day);
        if (!file.exists()) {
            file.mkdirs();
        }

        File file1 = new File(file, uuid + suffix);
        touxiang.transferTo(file1);


        ImageUtils imageUtils = new ImageUtils(file1.getAbsolutePath());
        imageUtils.resizeByWidth(100);


        return bookImage + year + "/" + month + "/" + day + "/" + uuid + suffix;
    }
}
